<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;

class BaoliaoDataSyncService
{
    protected $timeSharding;
    protected $popularitySharding;
    
    public function __construct(
        TimeBasedShardingService $timeSharding,
        PopularityBasedShardingService $popularitySharding
    ) {
        $this->timeSharding = $timeSharding;
        $this->popularitySharding = $popularitySharding;
    }
    
    /**
     * 同步数据到分表
     */
    public function syncToShardedTables($post)
    {
        $baseTable = 'baoliao_post';
        
        // 确定时间分表
        $timeSuffix = $this->timeSharding->getTableSuffixByTime(strtotime($post->create_time));
        $timeTable = "{$baseTable}_{$timeSuffix}";
        
        // 确定热度分表
        $hotSuffix = $this->popularitySharding->getTableSuffixByPopularity(
            $post->like_count, 
            $post->comment_count, 
            $post->view_count
        );
        $hotTable = "{$baseTable}_{$hotSuffix}";
        
        // 同步到时间分表
        $this->syncToTable($post, $timeTable);
        
        // 同步到热度分表
        $this->syncToTable($post, $hotTable);
    }
    
    /**
     * 同步数据到指定表
     */
    protected function syncToTable($post, $table)
    {
        // 检查记录是否已存在
        $exists = DB::table($table)->where('id', $post->id)->exists();
        
        if ($exists) {
            // 更新记录
            DB::table($table)->where('id', $post->id)->update((array) $post);
        } else {
            // 插入新记录
            DB::table($table)->insert((array) $post);
        }
    }
    
    /**
     * 重新同步所有数据
     */
    public function resyncAllData()
    {
        $baseTable = 'baoliao_post';
        $posts = DB::table($baseTable)->get();
        
        $bar = $this->output->createProgressBar(count($posts));
        
        foreach ($posts as $post) {
            $this->syncToShardedTables($post);
            $bar->advance();
        }
        
        $bar->finish();
        $this->info("\n所有数据同步完成");
    }
}
